import { watch } from 'vue';
export default function useSelect(formOptions: BaseOptionType[], cloneFormOptions: BaseOptionType[], formModel: FormModelType) {
	// 初始化全选
	const initSelectAll = () => {
		formOptions.forEach((opt) => {
			if ((opt.type === 'select' || opt.type === 'group-select') && opt.selectAll && opt.children) {
				onToggleSelectAll(opt, opt.children);
			}
		});
	};
	// 更新全选各状态
	// 有两组值，formModel[option.prop] 为实际选择的值；用于页面渲染；formModel[option.prop]为用于传给后台的值 formModel[option.prop]=[""]表示全选
	// 选择的项长度为0时，复选框是没有选择的状态 formModel[option.prop] = [];
	// 选择的项大于0 等于选项长度时，复选框为全选状态 小于选项长度时。复选框为"-"状态
	// 复选框全选状态clooneFormModel[option.prop]的值为所有选项的value值组成的数组
	// 复选框没有选择状态、全选状态  formModel[option.prop] 的值都为 [""]

	const updateSelectAllStatus = (opt: BaseOptionType, index: number) => {
		// 单选不做处理
		// option.children;
		// console.log('updateallstatus', cloneFormOptions);
		const selectArr = formModel[opt.prop] as [];
		const selectLen = selectArr?.length;
		let allLen = 0; //所有选项的长度
		const option = cloneFormOptions[index]; //取最初的 option
		if (option.children === undefined) {
			console.warn('updateSelectAllStatus-当前选项未定义----------');
			return;
		}
		//计算所有选项的长度
		if (option.type === 'group-select') {
			// 分组选择
			// selectArr  =selectArr.forEach()
			option.children?.forEach((opt: any) => {
				(opt.children as []).forEach(() => {
					allLen++;
				});
			});
		} else {
			// 其他选择
			allLen = option.children?.length;
		}
		//   已选项的长度总长度的对比
		if (selectLen === 0) {
			// formModel[option.prop] = [''];
			formModel[option.prop] = [];
		} else if (selectLen >= allLen) {
			// 全选
			// formModel[option.prop] = [''];
			formModel[option.prop] = selectArr;
		} else {
			formModel[option.prop] = selectArr;
		}

		updateSelectAllButtonStatus(opt);
	};

	// 更新全选按钮的状态
	// selectlist 必须包含所有 渲染的项 才是全选;全选时selectlist.length >= allLength
	// 如果 selectlist 包含部分渲染的项 按钮是 "-";
	// 如果 selectlist
	const updateSelectAllButtonStatus = (option: BaseOptionType) => {
		// 单选不做处理
		// option.children;
		console.log('updateSelectAllButtonStatus', option);
		if (formModel[option.prop] instanceof Array) {
			const selectArr = formModel[option.prop];
			let allLen = 0; //表示所有渲染项的长度
			let count = 0; // 表示 selectlist 包含多少个渲染的选项
			if (option.children === undefined) {
				console.warn('updateSelectAllStatus-当前选项未定义----------');
				return;
			}
			//计算所有选项的长度
			if (option.type === 'group-select') {
				// 分组选择
				// selectArr  =selectArr.forEach()
				option.children?.forEach((opt: any) => {
					(opt.children as OptionChidrenType[]).forEach((subOpt: OptionChidrenType) => {
						// allLen++;
						const value = option.selectKey ? subOpt[option.selectKey] : subOpt.value;

						if (selectArr.indexOf(value) > -1) {
							count++;
						}
						allLen++;
					});
				});
			} else {
				// 其他选择
				option.children?.forEach((opt: any) => {
					const value = option.selectKey ? opt[option.selectKey] : opt.value;
					if (selectArr.indexOf(value) > -1) {
						count++;
					}
					allLen++;
				});
			}
			//   已选项的长度总长度的对比
			if (count === 0) {
				// 表示取消全选
				option.selectAll = false;
				if (option.attrs) {
					option.attrs.indeterminate = false;
				}
			} else if (count >= allLen) {
				// 全选
				option.selectAll = true;
				if (option.attrs) {
					option.attrs.indeterminate = false;
				}
			} else {
				option.selectAll = false;
				if (option.attrs) {
					option.attrs.indeterminate = true;
				}
			}
		}

		// console.log('updateSelectAllStatus');
		// console.log('formModel', formModel[option.prop]);
		// console.log('formModel', formModel[option.prop]);
	};

	// 全选/取消全选的方法
	// 复选框全选状态 clooneFormModel[option.prop]的值为所有选项的value值组成的数组  formModel[option.prop] 的值都为 [""]
	// 复选框没有选择状态 clooneFormModel[option.prop]的值为[],formModel[option.prop] 的值为 [""]
	// 全选， selectlist =  实际渲染的项 + 之前选择的项（去重后）；
	// 取消全选 selectlist = selectlist - seachlist和实际渲染的项交集的部分
	const onToggleSelectAll = (option: BaseOptionType, children: OptionChidrenType[]) => {
		console.log('onToggleSelectAll', option.prop);
		// console.log('onToggleSelectAll', option.selectAll);
		// console.log('option.selectAll', children);
		// console.log('option.selectAll', option);
		const selectSet = new Set(formModel[option.prop]);
		if (option.selectAll) {
			// 全选
			// formModel[option.prop] = [''];

			if (option.type === 'group-select') {
				// 分组下拉，children是个二维数组
				// let a:OptionChidrenType = [];
				// selectArr = new Set(selectArr);
				children?.map((opt) => {
					// debugger
					(opt.children as Array<Record<string, unknown>>).map((subOpt: any) => {
						// if()
						// (formModel[option.prop] as Array<Record<string, unknown>>).add(subOpt.value);
						if (option.selectKey) {
							selectSet.add(subOpt[option.selectKey]);
						} else {
							selectSet.add(opt.value);
							selectSet.add(subOpt.value);
						}
					});
				});
			} else {
				// 其他下拉
				children?.map((opt) => {
					if (option.selectKey) {
						selectSet.add(opt[option.selectKey]);
					} else {
						selectSet.add(opt.value);
					}
				});
				// formModel[option.prop] = children?.map((opt) => (option.selectKey ? opt[option.selectKey] : opt.value));
			}
			// formModel[option.prop] = Array.from(selectSet);
			// console.log('formModel[option.prop]', formModel[option.prop]);
		} else {
			// 取消全选
			// let selectList = formModel[option.prop];
			// selectSet.forEach(opt => {

			// })
			if (option.type === 'group-select') {
				// 分组下拉，children是个二维数组
				children?.map((opt) => {
					// debugger
					(opt.children as Array<Record<string, unknown>>).map((subOpt: any) => {
						// if()
						// (formModel[option.prop] as Array<Record<string, unknown>>).add(subOpt.value);
						selectSet.add(subOpt.value);
						const value = option.selectKey ? subOpt[option.selectKey] : subOpt.value;
						selectSet.has(value) && selectSet.delete(value);
					});
				});
			} else {
				// 其他下拉
				children?.map((opt) => {
					const value = option.selectKey ? opt[option.selectKey] : opt.value;
					selectSet.has(value) && selectSet.delete(value);
				});
				// formModel[option.prop] = children?.map((opt) => (option.selectKey ? opt[option.selectKey] : opt.value));
			}
			// formModel[option.prop] = [''];
			formModel[option.prop] = [];
			// formModel[option.prop] = [];
		}
		formModel[option.prop] = Array.from(selectSet);
		updateSelectAllButtonStatus(option);
	};

	// select的搜索过滤方法
	// 要区分分组下拉和普通下拉
	const onSelectFilter = (query: string, option: BaseOptionType, index: number) => {
		let result: any;
		if (query) {
			if (option.type === 'group-select') {
				// 分组下拉
				option.children?.forEach((opt) => {
					const arr: OptionChidrenType[] = [];
					(opt.children as Array<Record<string, unknown>>).forEach((subOpt: any) => {
						//   subOpt.label.indexOf()
						// debugger

						if (subOpt.label.toLowerCase().indexOf(query.toLowerCase()) > -1) {
							arr.push(subOpt);
							// debugger
						}
					});
					// 如果arr有长度才存进result
					if (arr.length) {
						result.push({
							label: opt.label,
							children: arr,
						});
					}
				});
			} else {
				// 普通下拉
				result = option.children?.filter((opt) => {
					return opt.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
				});
			}
		} else {
			const initOption: BaseOptionType | undefined = cloneFormOptions.find((opt) => opt.prop === option.prop);
			if (initOption instanceof Object && initOption.children instanceof Array) {
				// console.log(11111111, initOption.children)
				result = JSON.parse(JSON.stringify(initOption.children));
			}
		}
		formOptions[index].children = result || [];
		if (option.attrs?.multiple) {
			updateSelectAllStatus(formOptions[index], index);
		}
	};
	// 远程搜索，需要开启了remote才会生效
	const onRemoteSelectFilter = async (
		query: string,
		option: BaseOptionType,
		index: number,
		fetSetOption: (option: BaseOptionType, name: string, params: any) => any
	) => {
		if (!option.api) {
			throw Error('请设置请求api');
		}
		if (query !== '') {
			if (option.attrs) {
				option.attrs.loading = true;
			}
			const arr = await fetSetOption(option, option.api.name, query);

			cloneFormOptions[index].children = arr as [];
			cloneFormOptions[index].children = option.children;
			if (option.attrs) {
				option.attrs.loading = false;
			}
		} else {
			option.children = [];
		}
	};

	//   下拉组件全选复选框值改变事件
	const onCheckboxChange = (e: any, option: BaseOptionType) => {
		// select.focus();
		if (option.children instanceof Array) {
			onToggleSelectAll(option, option.children);
		}
	};
	// 更新Option
	const updateOptions = (options: BaseOptionType[], cloneOptions: BaseOptionType[]) => {
		formOptions = options;
		cloneFormOptions = cloneOptions;
	};
	return {
		updateSelectAllStatus,
		onCheckboxChange,
		onRemoteSelectFilter,
		onSelectFilter,
		onToggleSelectAll,
		updateOptions,
		initSelectAll,
	};
}
